import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/permissionGroup.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_ahj_app/base/utils/HttpNoTokenUtils.dart';

import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_ahj_app/base/bean/show_files_bean.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import '../date_util.dart';
import '../mTopBar.dart';
import 'OpenFileUtils.dart';

class DownFilePage2 extends StatefulWidget {
  String downUrl, filePath, fileName;

  DownFilePage2(this.downUrl, this.filePath, this.fileName);

  @override
  State<StatefulWidget> createState() => DownFilePage2State();
}

class DownFilePage2State extends State<DownFilePage2> {
  String _btnText = "开始下载";
  bool _isDownLoading = false; // 是否正在下载
  int _progress = 0, _count = 0, _total = 0;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: MTopBar(title: "文件下载").create(),
        body: _body(),
      ),
      onWillPop: () => _back(),
    );
  }

  _back() {
    if (_isDownLoading) {
      //正在下载
      _showDialog(context);
    } else {
      Navigator.pop(context);
    }
  }
  ///获得图片路径
  _getImagePath(type) async {
    var params = {"a": "a"};

    ///fileName  文件名
    /// type  是否是视频1:是 0:不是
    String url = HttpBaseConst.serverUrl +
        HttpBaseConst.downloadPath +
        "?" +
        "fileName=" +
        widget.downUrl +
        "&type=0";
    HttpNoTokenUtils.httpGet(url, params, (result) {
      print(result);

      ShowFilesBean showFilesBean = ShowFilesBean.fromJson(json.decode(result));

      print("我是fileUrl" + showFilesBean.data.fileUrl);
      widget.downUrl=showFilesBean.data.fileUrl;
      if(type=="2"){
        yulan();
      }else{
        _down();
      }

    }, context: context);
  }
  // 提示框
  _showDialog(BuildContext context) {
    StatefulBuilder sb = StatefulBuilder(
      builder: (context, mSetState) {
        return new AlertDialog(
          title: new Text("温馨提示"),
          content: new Text("有文件正在下载，是否中断下载？"),
          actions: <Widget>[
            FlatButton(
                child: Text("是"),
                onPressed: () {
                  Navigator.of(context).pop();
                  _cancleDown();
                }),
            FlatButton(
                child: new Text("否"),
                onPressed: () {
                  Navigator.of(context).pop();
                })
          ],
        );
      },
    );

    showDialog(
        context: context, barrierDismissible: false, builder: (context) => sb);
  }

  _body() {
    Widget body = Padding(
      padding: EdgeInsets.only(
          top: Dimens.dimens96, left: Dimens.dimens48, right: Dimens.dimens48),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Image.asset(
            "img/icon_file.png",
            width: Dimens.dimens80,
            height: Dimens.dimens80,
          ),
          Container(height: Dimens.dimens16),
          Text(
            widget.fileName,
            style: TextStyle(
                color: SQColor.per87Black, fontSize: Dimens.textSize44),
          ),
          Expanded(flex: 1, child: Text("")),

//          new Container(
//            child: new Row(
//              children: [
//                MaterialButton(
//                  shape: RoundedRectangleBorder(
//                      borderRadius:
//                      BorderRadius.all(Radius.circular(Dimens.dimens8))),
//                  color: SQColor.theme_color,
//                  textColor: SQColor.white,
//                  minWidth: double.infinity,
//                  height: Dimens.dimens48,
//                  onPressed: () => widget.downUrl.startsWith("http")?yulan():  _getImagePath("1"),
//                  child: Text(
//                    "查看",
//                    style: TextStyle(fontSize: Dimens.textSize28),
//                  ),
//                ),
//               new Container(
//                 child: new    Offstage(
//                   offstage: _isDownLoading,
//                   child: MaterialButton(
//                     shape: RoundedRectangleBorder(
//                         borderRadius:
//                         BorderRadius.all(Radius.circular(Dimens.dimens8))),
//                     color: SQColor.theme_color,
//                     textColor: SQColor.white,
//                     minWidth: double.infinity,
//                     height: Dimens.dimens48,
//                     onPressed: () => _btnText == "开始下载" ?  widget.downUrl.startsWith("http")?   _down():  _getImagePath("1") : _open(),
//                     child: Text(
//                       _btnText,
//                       style: TextStyle(fontSize: Dimens.textSize28),
//                     ),
//                   ),
//                 ),
//               ) ,
//              ],
//            ),
//          ),
          Offstage(
            offstage: _isDownLoading,
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                  borderRadius:
                  BorderRadius.all(Radius.circular(Dimens.dimens8))),
              color: SQColor.theme_color,
              textColor: SQColor.white,
              minWidth: double.infinity,
              height: Dimens.dimens48,
              onPressed: () =>widget.downUrl.startsWith("http")?yulan():  _getImagePath("2"),
              child: Text(
                "预览",
                style: TextStyle(fontSize: Dimens.textSize28),
              ),
            ),
          ),
          new Container(
            height: 12,
          ),
          Offstage(
            offstage: _isDownLoading,
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                  borderRadius:
                      BorderRadius.all(Radius.circular(Dimens.dimens8))),
              color: SQColor.theme_color,
              textColor: SQColor.white,
              minWidth: double.infinity,
              height: Dimens.dimens48,
              onPressed: () =>_btnText == "开始下载" ?  widget.downUrl.startsWith("http")?   _down():  _getImagePath("1") : _open(),
              child: Text(
                _btnText,
                style: TextStyle(fontSize: Dimens.textSize28),
              ),
            ),
          ),
          Offstage(
            offstage: !_isDownLoading,
            child: Text(
              "下载进度：$_progress%",
              style: TextStyle(
                  color: SQColor.per60Black, fontSize: Dimens.textSize28),
            ),
          ),
          Container(height: Dimens.dimens96)
        ],
      ),
    );
    return body;
  }
  yulan(){
    if(widget.downUrl.contains(".png")||widget.downUrl.contains(".jpg")||widget.downUrl.contains(".JPG")||widget.downUrl.contains(".PNG")){
      List<String> filePath = [];
      int position = 0;
      filePath.add(widget.downUrl);

      Navigator.pushNamed(context, "/ShowImage",
          arguments: {'position': position, 'filePath': filePath});

    }else if (widget.downUrl.contains(".doc") ||
        widget.downUrl.contains(".docx") ||
        widget.downUrl.contains(".xls") ||
        widget.downUrl.contains(".xlsx") ||
        widget.downUrl.contains(".XLS") ||
        widget.downUrl.contains(".XLSX") ||
        widget.downUrl.contains(".ppt") ||
        widget.downUrl.contains(".pdf") ||
        widget.downUrl.contains(".pptx")) {


      if (Platform.isIOS) {
        Navigator.pushNamed(context, "/WebViewUntil",
            arguments: {"title": "预览", "url": widget.downUrl});
      } else {
        // String encodeUrl = Uri.encodeComponent(,woye
        //
        //     widget.downUrl);


        // var dataurl=widget.downUrl+"?time="+(DateUtil.getNowDateMs().toString());
        String encodeUrl = Uri.encodeComponent(base64Encode(utf8.encode(widget.downUrl)));

        String webUrl =
            "https:\u002f\u002ffilesvc.anhuanjia.com\u002fonlinePreview?url=$encodeUrl";

        // String webUrl =
        //     "http:\u002f\u002fdocs.xinanyun.cn\u002fop\u002fembed.aspx?src=$encodeUrl";


        Navigator.pushNamed(context, "/WebViewPDF",
            arguments: {
              "title": "预览"
                  '',
              "url": webUrl,
              "pdf": widget.downUrl
                  .toLowerCase()
                  .endsWith(".pdf")
                  ? true
                  : false,
              "withZoom": true,
            });
      }


    }else if(widget.downUrl.contains(".doc")||widget.downUrl.contains(".docx")){

    }else if(widget.downUrl.contains(".xls")){

    }else if(widget.downUrl.contains(".ppt")){

    }else if(widget.downUrl.contains(".pdf")){

    }else{
      ToastUtils.showToast("该格式暂不支持预览");
    }

  }
  _cancleDown() async {
    // 创建文件夹
//    File file = File(widget.filePath);
//    if (await file.exists()) {
//      // 附件已经存在，删除文件
//      await file.delete();
//    }
    cancelToken.cancel("cancelled");
    Navigator.pop(context); //关闭对话框
  }

  _open() {
    print("openFile ${widget.filePath}");
    if (Platform.isAndroid) {
      OpenFileUtils.open(widget.filePath);
    } else if (Platform.isIOS) {
      OpenFileUtils.open(widget.filePath);
    }
  }

  CancelToken cancelToken = new CancelToken();

  _down() async {
    // if (Platform.isAndroid) {
    setState(() {
      _isDownLoading = true;
    });
    String result =
    await PerUtils.checkPermission(context, [Permission.storage]);
    if (result == "1") {
      print(widget.downUrl);
      print(widget.filePath);
      Dio dio = new Dio();
      Map<String, dynamic> headers = new Map();
      headers['COOKIE'] = "ASP.NET_SessionId=" +
          HttpBaseConst.sessionId +
          "; " +
          "__sid=" +
          UserInfoUtils.getSID() +
          "; _mid=" +
          UserInfoUtils.getMID().toString() +
          "; apptype=1";
//        headers['Accept'] = "text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//        headers['Accept-Encoding'] = "gzip, deflate";
//        headers['Accept-Language'] = "zh-CN,zh;q=0.8";
      headers['User-Agent'] =
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 Hutool";
      dio.interceptors
          .add(InterceptorsWrapper(onRequest: (RequestOptions options,RequestInterceptorHandler requestInterceptorHandler) async {
        options.headers = headers;
        return requestInterceptorHandler.next(options); //continue
      }, onResponse: (Response response,dd) {
        return dd.next(response); // continue
      }, onError: (DioError e,dd) {
        print(e.toString());
        setState(() {
          _count = 0;
          _total = 0;
          _progress = 0;
          _isDownLoading = false;
          _btnText = "开始下载";
        });
        return dd.next(e); //continue
      }));
      try {
        await dio.download(widget.downUrl, widget.filePath,
            cancelToken: cancelToken, onReceiveProgress: (count, total) {
              setState(() {
                _count = count;
                _total = total;
                try {
                  _progress = (_count / _total * 100).toInt();
                } catch (e) {
                  _progress = 0;
                }
                if (count > 0 && total > 0 && count == total) {
                  // 下载完毕
                  _count = 0;
                  _total = 0;
                  _progress = 0;
                  _isDownLoading = false;
                  _btnText = "打开文件";
                }
              });
            });
      } on DioError catch (e) {

      }
    }
    // } else if (Platform.isIOS) {}
  }
}
